<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { HandCardTypeApi } from '#/api/spa/handcard/type';

import { Page, useVbenModal } from '@vben/common-ui';
import { message,Tabs } from 'ant-design-vue';
import Form from './modules/form.vue';


import { ref, computed } from 'vue';
import { $t } from '#/locales';
import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import { getHandCardTypePage, deleteHandCardType, exportHandCardType } from '#/api/spa/handcard/type';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { useGridColumns, useGridFormSchema } from './data';
// 列表图片路径统一处理：沿用 goods-binder 的前缀规则
function withImgPrefix(path?: string) {
  const p = path || '';
  if (!p) return '';
  if (/^https?:\/\//i.test(p) || /^\/shop-img-api\//.test(p)) return p;
  return `/shop-img-api/${p.replace(/^\/+/, '')}`;
}


const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});


/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建手牌类型 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑手牌类型 */
function handleEdit(row: HandCardTypeApi.HandCardType) {
  formModalApi.setData(row).open();
}


/** 删除手牌类型 */
async function handleDelete(row: HandCardTypeApi.HandCardType) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    key: 'action_key_msg',
  });
  try {
    await deleteHandCardType(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_key_msg',
    });
    onRefresh();
  } finally {
    hideLoading();
  }
}


/** 导出表格 */
async function handleExport() {
  const data = await exportHandCardType(await gridApi.formApi.getValues());
  downloadFileFromBlobPart({ fileName: '手牌类型.xls', source: data });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getHandCardTypePage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<HandCardTypeApi.HandCardType>,
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="onRefresh" />

    <Grid table-title="手牌类型列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: $t('ui.actionTitle.create', ['手牌类型']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['spa:hand-card-type:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['spa:hand-card-type:export'],
              onClick: handleExport,
            },
          ]"
        />
      </template>
      <template #goodsInfo="{ row }">
        <div style="display:flex;flex-wrap:wrap;gap:8px;align-items:center;">
          <template
            v-for="(item, idx) in (Array.isArray(row.goodsInfo) ? row.goodsInfo : (() => { try { return JSON.parse(row.goodsInfo || '[]') } catch { return [] } })())"
            :key="idx"
          >
            <div style="display:flex;align-items:center;gap:6px;max-width:260px;">
              <img
                :src="withImgPrefix(item?.cover)"
                :alt="item?.goodsName || ''"
                style="width:18px;height:18px;object-fit:cover;border-radius:2px;background:#f5f5f5;"
              />
              <span style="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                {{ item?.goodsName || '' }}
              </span>
            </div>
          </template>
        </div>
      </template>
      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['spa:hand-card-type:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['spa:hand-card-type:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>

  </Page>
</template>
